package com.bluesky.plum.domain.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bluesky.plum.domain.repository.Entity;
import com.bluesky.plum.domain.repository.search.condition.Condition;

/**
 * wrap a Hibernate session to a Repository
 * 
 * @author jack
 * 
 * @param <Entity>
 */
public class HibernateRepositorySupport extends HibernateDaoSupport {

	public HibernateRepositorySupport() {

	}

	
	public synchronized void add(Object entity) {
		getSession().save(entity);
	}

	
	public synchronized void remove(Object entity) {

		getSession().delete(entity);
	}

	
	public synchronized List<Object> getAll(Class clazz) {
		//return getHibernateTemplate().loadAll(clazz);
		String hql = "from "+ clazz.getSimpleName();
		System.out.println(hql);
		return getHibernateTemplate().find(hql);
	}

	
	public synchronized Object getByIndex(Class clazz,int index) {

		return getAll(clazz).get(index);
	}

	
	public synchronized List<Object> getByPage(Class clazz,int pageLength, int pageNumber) {

		List<Object> list = getAll(clazz);
		List<Object> rslt = new ArrayList<Object>();

		int start = pageLength * pageNumber;
		if (start >= getCount(clazz))
			throw new RuntimeException("the page do not exist");

		int end = start + pageLength;
		if (end >= list.size())
			end = list.size();

		for (int i = start; i < end; i++)
			rslt.add(list.get(i));

		return rslt;
	}


	public synchronized int getCount(Class clazz) {

		return getAll(clazz).size();
	}


	public synchronized void update(Object oldEntity, Object newEntity) {
		// copy object
		// FieldUtil2.copyFields(newEntity, oldEntity);
		try {
			PropertyUtils.copyProperties(newEntity, oldEntity);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	
	public List<Object> find(Class clazz,Condition condition) {
		// TODO Auto-generated method stub
		return null;
	}


	public boolean equals(Object obj1, Object obj2) {
		Entity e1 = (Entity) obj1;
		Entity e2 = (Entity) obj2;
		return e1.getId().equals(e2.getId());
	}

	public static void main(String[] args) {
		// Page page =
		// HibernatePage.getHibernatePageInstance(hibQuery,pageNumber,pageSize);
		// for (Object yourType : page.getThisPageElements()) {
		// //YourType yourType =
		//		
		// }
	}

}
